package com.contactmanager;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

public class AllContacts extends ListActivity {

	static final String EXTRA_MESSAGE = "";
	protected static final Sync Sync = null;
	int groupsSelectedID = 0;

	ArrayList<Contact> contacts = new ArrayList<Contact>();
	ArrayList<Group> groups = new ArrayList<Group>();
	String currentSearch = "";
	AlertDialog dialog;
	Context context;
	EditText txtUsername;
	String globalUser;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// Restore preferences
		SharedPreferences settings = getSharedPreferences("preferences", 0);
		int theme = settings.getInt("curTheme", R.style.AppBaseTheme);
		globalUser=settings.getString("curUser","");
		System.out.println(theme);
		setTheme(theme);
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
				WindowManager.LayoutParams.FLAG_FULLSCREEN);

		// Get all contacts from database
		new GetAllRowsTask().execute();
		// Get all groups from database
		new GetAllGroupsTask().execute();

		setContentView(R.layout.activity_all_contacts);

		// Alert Dialog to Sign in or Register for the cloud
		AlertDialog.Builder builder = new AlertDialog.Builder(AllContacts.this);
		LayoutInflater inflater = AllContacts.this.getLayoutInflater();

		builder.setView(inflater.inflate(R.layout.dialog_layout, null));

		builder.setPositiveButton("Register",
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
						// User clicked Register button

						txtUsername = (EditText) ((AlertDialog) dialog)
								.findViewById(R.id.username);
						Log.v("EditText", txtUsername.getText().toString());
						String username = txtUsername.getText().toString();

						EditText txtPassword = (EditText) ((AlertDialog) dialog)
								.findViewById(R.id.password);
						String password = txtPassword.getText().toString();
						System.out.println(password);

						tryRegister(username, password);
					}

					private void tryRegister(String username, String password) {

						HttpClient httpclient = new DefaultHttpClient();
						HttpPost httppost = new HttpPost(
								"http://softeng.cs.uwosh.edu/students/kempk79/functions.php");

						try {
							// Add your data
							List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(
									4);
							nameValuePairs.add(new BasicNameValuePair(
									"register", "true"));
							nameValuePairs.add(new BasicNameValuePair(
									"username", username));
							nameValuePairs.add(new BasicNameValuePair(
									"password", password));
							nameValuePairs.add(new BasicNameValuePair(
									"confpassword", password));
							httppost.setEntity(new UrlEncodedFormEntity(
									nameValuePairs));

							// Execute HTTP Post Request
							HttpResponse response = httpclient
									.execute(httppost);
							String result = EntityUtils.toString(response
									.getEntity());
							if (!result.equals("Success")) {
								context = getApplicationContext();
								Toast toast = Toast.makeText(context, result,
										400);
								toast.show();
							} else {
								new update().execute(username);
								changeUser(username);
								
							}

						} catch (ClientProtocolException e) {
							// TODO Auto-generated catch block
						} catch (IOException e) {
							// TODO Auto-generated catch block
						}
					}
				});
		builder.setNeutralButton("Sign-in",
				new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						// User Clicked sign in
						txtUsername = (EditText) ((AlertDialog) dialog)
								.findViewById(R.id.username);
						Log.v("EditText", txtUsername.getText().toString());
						String username = txtUsername.getText().toString();

						EditText txtPassword = (EditText) ((AlertDialog) dialog)
								.findViewById(R.id.password);
						String password = txtPassword.getText().toString();
						System.out.println(password);

						tryLogin(username, password);
					}

					private void tryLogin(String username, String password) {

						// Create a new HttpClient and Post Header
						HttpClient httpclient = new DefaultHttpClient();
						HttpPost httppost = new HttpPost(
								"http://softeng.cs.uwosh.edu/students/kempk79/functions.php");

						try {
							// Add your data
							List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(
									3);
							nameValuePairs.add(new BasicNameValuePair("login",
									"true"));
							nameValuePairs.add(new BasicNameValuePair(
									"username", username));
							nameValuePairs.add(new BasicNameValuePair(
									"password", password));
							httppost.setEntity(new UrlEncodedFormEntity(
									nameValuePairs));

							// Execute HTTP Post Request
							HttpResponse response = httpclient
									.execute(httppost);
							String result = EntityUtils.toString(response
									.getEntity());
							if (!result.equals("Success")) {
								context = getApplicationContext();
								Toast toast = Toast.makeText(context, result,
										400);
								toast.show();
							} else {
								new update().execute(username);
								if (globalUser.equals("")||!globalUser.equals(username))
									changeUser(username);
								context = getApplicationContext();
								Toast toast = Toast.makeText(context, result,
										400);
								toast.show();
								new GetAllRowsTask().execute();
							}

						} catch (ClientProtocolException e) {
							// TODO Auto-generated catch block
						} catch (IOException e) {
							// TODO Auto-generated catch block
						}

					}
				});
		builder.setNegativeButton("Cancel",
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
						// User cancelled the dialog
					}
				});
		builder.setTitle("Sync with the Cloud");
		// LayoutInflater inflater = getLayoutInflater();
		// builder.setView(inflater.inflate(R.layout.dialog_layout, null));
		dialog = builder.create();

		ImageButton settingsButton = (ImageButton) findViewById(R.id.settingsButton);
		settingsButton.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				Intent myIntent2 = new Intent(AllContacts.this,
						EditGroups.class);
				startActivityForResult(myIntent2, 0);
			}
		});

		ImageButton addContactBtn = (ImageButton) findViewById(R.id.imageButton1);
		addContactBtn.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				Intent myIntent = new Intent(AllContacts.this, AddContact.class);
				startActivityForResult(myIntent, 0);
			}
		});

		Spinner spinner = (Spinner) findViewById(R.id.groups);
		spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
			@Override
			public void onItemSelected(AdapterView<?> parentView,
					View selectedItemView, int position, long id) {
				Spinner spinner = (Spinner) findViewById(R.id.groups);
				groupsSelectedID = spinner.getSelectedItemPosition();

				if (groupsSelectedID == 0) {
					new GetAllRowsTask().execute();
				} else {
					new GetFilteredRowsTask().execute();
				}
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
				return;
			}

		});

		TextView searchBar = (TextView) findViewById(R.id.search);
		searchBar.addTextChangedListener(new TextWatcher() {

			@Override
			public void afterTextChanged(Editable s) {
				// TODO Auto-generated method stub

			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				Log.d("CM", "Search was for: " + s.toString());
				new SearchContactsTask().execute(s);
			}

		});
	}

	@Override
	protected void onResume() {
		super.onResume();

		// Get all contacts from database
		new GetAllRowsTask().execute();
		// Get all groups from database
		new GetAllGroupsTask().execute();
	}

	public void onStop() {
		super.onStop();
		new update().execute(globalUser);
	}

	@Override
	public void onListItemClick(ListView list, View view, int position, long id) {
		super.onListItemClick(list, view, position, id);
		Contact a = (Contact) list.getAdapter().getItem(position);
		try {
			Intent intent = new Intent(this, ViewContacts.class);
			intent.putExtra("Contact", a);
			startActivity(intent);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == 1) {
			new GetAllRowsTask().execute();
		}
	}

	private class GetAllRowsTask extends
			AsyncTask<Void, Integer, ArrayList<Contact>> {

		@Override
		protected ArrayList<Contact> doInBackground(Void... nothing) {

			ContactsDataSource cds = new ContactsDataSource(AllContacts.this);

			cds.open();

			ArrayList<Contact> contacts = cds.getAllContacts();

			cds.close();

			Collections.sort(contacts, new Comparator<Contact>() {
				public int compare(Contact c1, Contact c2) {
					return c1.getName().compareToIgnoreCase(c2.getName());
				}
			});

			return contacts;
		}

		@Override
		protected void onPostExecute(ArrayList<Contact> contactList) {
			setListAdapter(new ArrayAdapter<Contact>(AllContacts.this,
					android.R.layout.simple_list_item_1, contactList));
			AllContacts.this.contacts = contactList;
		}

	}

	private class GetFilteredRowsTask extends
			AsyncTask<Void, Integer, ArrayList<Contact>> {

		@Override
		protected ArrayList<Contact> doInBackground(Void... nothing) {

			ContactsDataSource cds = new ContactsDataSource(AllContacts.this);

			cds.open();
			ArrayList<Contact> contacts = cds
					.getContactsGroup(groupsSelectedID);
			// updated to use the getContactsGroup function because allcontacts
			// is now a group
			// ArrayList<Contact> contacts = cds.getAllContacts();

			cds.close();

			Collections.sort(contacts, new Comparator<Contact>() {
				public int compare(Contact c1, Contact c2) {
					return c1.getName().compareToIgnoreCase(c2.getName());
				}
			});

			return contacts;
		}

		@Override
		protected void onPostExecute(ArrayList<Contact> contactList) {
			setListAdapter(new ArrayAdapter<Contact>(AllContacts.this,
					android.R.layout.simple_list_item_1, contactList));
			AllContacts.this.contacts = contactList;
		}

	}

	private class SearchContactsTask extends
			AsyncTask<CharSequence, Integer, ArrayList<Contact>> {

		@Override
		protected ArrayList<Contact> doInBackground(CharSequence... searchChars) {
			ArrayList<Contact> search = new ArrayList<Contact>();

			for (Contact c : AllContacts.this.contacts) {
				if (c.getName().contains(searchChars[0])
						|| searchChars.toString().equals("")) {
					search.add(c);
					Log.d("CM", c.getName() + " " + c.getGroup());
				}
			}
			return search;
		}

		@Override
		protected void onPostExecute(ArrayList<Contact> contactList) {
			setListAdapter(new ArrayAdapter<Contact>(AllContacts.this,
					android.R.layout.simple_list_item_1, contactList));
		}

	}

	private class update extends AsyncTask<String, Void, Void> {
		@Override
		protected Void doInBackground(String... params) {
			Sync s = new Sync();
			ContactsDataSource cds = new ContactsDataSource(AllContacts.this);
			cds.open();
			new GetAllRowsTask().execute();
			new GetAllGroupsTask().execute();
			s.update(params[0], getUpdateTime(), contacts,groups, cds,
					globalUser);
			cds.close();
			new GetAllRowsTask().execute();
			new GetAllGroupsTask().execute();
			
			// Get all groups from database
			;
			return null;
		}
	}

	private class GetAllGroupsTask extends
			AsyncTask<Void, Integer, ArrayList<Group>> {

		@Override
		protected ArrayList<Group> doInBackground(Void... nothing) {

			ContactsDataSource cds2 = new ContactsDataSource(AllContacts.this);

			cds2.open();

			ArrayList<Group> groups = cds2.getAllGroups();

			cds2.close();

			return groups;
		}

		@Override
		protected void onPostExecute(ArrayList<Group> groupList) {
			Spinner spinner = (Spinner) findViewById(R.id.groups);
			ArrayAdapter<Group> adapter = new ArrayAdapter<Group>(
					AllContacts.this,
					android.R.layout.simple_spinner_dropdown_item, groupList);
			spinner.setAdapter(adapter);
		}

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.overflow_menu, menu);
		dialog.show();
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle item selection
		switch (item.getItemId()) {
		case R.id.theme1:
			changeTheme(R.style.AppBaseTheme); // change theme
			return true;
		case R.id.theme2:
			changeTheme(R.style.AppDarkTheme); // change theme
			return true;
		case R.id.theme3:
			changeTheme(R.style.AppLightHolo); // change theme
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}

	public void changeTheme(int themeChoice) {
		SharedPreferences settings = getSharedPreferences("preferences", 0);
		SharedPreferences.Editor editor = settings.edit();
		editor.putInt("curTheme", themeChoice);

		// Commit the edits!
		editor.commit();

		Intent intent = getIntent();
		finish();
		startActivity(intent);
	}
	
	public void changeUser(String user) {
		SharedPreferences settings = getSharedPreferences("preferences", 0);
		SharedPreferences.Editor editor = settings.edit();
		editor.putString("curUser", user);

		// Commit the edits!
		editor.commit();

		Intent intent = getIntent();
		finish();
		startActivity(intent);
	}


	public long getUpdateTime(){
		SharedPreferences settings = getSharedPreferences("preferences", 0);
		long time = settings.getLong("lastUpdate", -1);
		System.out.println("lastUpdate"+time);
		return time;
	}

}
